#!/bin/bash

# 修复换行符问题（如果脚本是从Windows编辑的）
sed -i 's/\r$//' "$0"

# 检查root权限
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用sudo或root用户运行此脚本"
    exit 1
fi

# 读取用户输入
read -p "请输入虚拟网名称: " community
read -p "请输入本机要使用的IP地址: " name
read -p "请输入服务器地址及端口: " host

echo "可选版本: 3.0-stable, 2.8-stable, 2.6-stable, 2.4-stable"
read -p "请选择N2N版本: " n2n_version

# 安装依赖
echo "正在安装依赖..."
apt-get update
apt-get install -y git build-essential libssl-dev cmake net-tools

# 下载并编译n2n
echo "正在下载并编译n2n..."
if [ ! -d "n2n" ]; then
    git clone https://github.com/ntop/n2n.git
fi

cd n2n || { echo "无法进入n2n目录"; exit 1; }

case $n2n_version in
    "3.0-stable") git checkout 3.0-stable ;;
    "2.8-stable") git checkout 2.8-stable ;;
    "2.6-stable") git checkout 2.6-stable ;;
    "2.4-stable") git checkout 2.4-stable ;;
    *) echo "无效版本"; exit 1 ;;
esac

mkdir -p build
cd build
cmake ..
make
make install

# 创建配置文件
echo "创建配置文件..."
mkdir -p /etc/n2n
cat > /etc/n2n/edge.conf <<EOF
-a $name
-c $community
-l $host
EOF

# 创建systemd服务
echo "创建systemd服务..."
cat > /etc/systemd/system/n2n-edge.service <<EOF
[Unit]
Description=N2N Edge Service
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/sbin/edge -f -r -a $name -c $community -l $host
Restart=always
RestartSec=5s
User=root
Group=root

[Install]
WantedBy=multi-user.target
EOF

# 启用并启动服务
echo "启用并启动服务..."
systemctl daemon-reload
systemctl enable n2n-edge
systemctl start n2n-edge

# 检查服务状态
echo "检查服务状态..."
sleep 3
systemctl status n2n-edge --no-pager

# 创建管理脚本
echo "创建管理脚本..."
cat > /usr/local/bin/n2n-control <<EOF
#!/bin/bash
case \$1 in
    start) systemctl start n2n-edge ;;
    stop) systemctl stop n2n-edge ;;
    restart) systemctl restart n2n-edge ;;
    status) systemctl status n2n-edge --no-pager ;;
    *) echo "用法: n2n-control {start|stop|restart|status}" ;;
esac
EOF

chmod +x /usr/local/bin/n2n-control

echo "安装完成！"
echo "您可以使用以下命令管理n2n服务:"
echo "  n2n-control start    # 启动服务"
echo "  n2n-control stop     # 停止服务"
echo "  n2n-control restart  # 重启服务"
echo "  n2n-control status   # 查看状态"